package com.mutouren.common.session.impl;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import com.google.common.cache.Cache;
import com.mutouren.common.cache.local.GuavaCacheUtils;
import com.mutouren.common.session.Session;
import com.mutouren.common.session.SessionConfig;
import com.mutouren.common.session.UserInfo;
import com.mutouren.common.utils.CookieUtils;
import com.mutouren.common.utils.StringUtils;

public class LocalSessionImpl implements Session {
		
	private final static int maxNumSize = 100000;
	private static Cache<String, UserInfo> cache = 
			GuavaCacheUtils.createCache(SessionConfig.sessionTime, TimeUnit.SECONDS, maxNumSize);

	@Override
	public UserInfo get(HttpServletRequest request) {
		UserInfo result = null;
		
		String sessionId = CookieUtils.get(request, SessionConfig.cookieName);
		if (StringUtils.isNullOrEmpty(sessionId)) return null; 
		
		result = cache.getIfPresent(sessionId);
		if (result == null) return null;
		
		long runTime = (new Date().getTime() - result.getLoginTime()) / 1000;
		if (runTime > SessionConfig.sessionMaxTime) {
			cache.invalidate(sessionId); // not do cookie
			return null;
		}
		
		return result;
	}

	@Override
	public void set(HttpServletRequest request, String sessionId, UserInfo userInfo) {
		cache.put(sessionId, userInfo);		
	}

	@Override
	public void delete(HttpServletRequest request) {
		String sessionId = CookieUtils.get(request, SessionConfig.cookieName);
		if (StringUtils.isNullOrEmpty(sessionId)) return;
		
		cache.invalidate(sessionId);
	}

}
